package Graph;

public class Info {
    /*相邻矩阵法表示一个无向图，
    图为V={1,2,3,4,5};E={(1,2),(1,5),(2,3),(2,4),(3,4),(3,5),(4,5)}*/
    public static void functionOne(int[][] data,int m){
        //声明矩阵arr并初始化
        int arr[][] = new int[m][m];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = 0;
            }
        }

        for (int i = 0; i < data.length; i++) { //读取图形数据
            for (int j = 0; j < m; j++) { //填入矩阵
                for (int k = 0; k < m; k++) {
                    int tmpi = data[i][0];//tmpi为起始顶点
                    int tmpj = data[i][1];//tmpj为终止顶点
                    arr[tmpi][tmpj] = 1;//有边的点填入1
                }
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < m; j++){
                System.out.print("["+arr[i][j]+"]");}
            System.out.println("\n");
        }
    }

    /*相邻表法*/
    static class Node{
        int x;
        Node next;
        public Node(int x) {
            this.x = x;
            this.next = null;
        }
    }

    static class GraphLink{
        public Node first;
        public Node last;
        public boolean isEmpty(){
            return first == null;
        }
        public void print(){
            Node current = first;
            while (current != null){
                System.out.print("["+current.x+"]");
                current = current.next;
            }
            System.out.println();
        }
        public void insert(int x){
            Node newNode = new Node(x);
            if (isEmpty()){
                first = newNode;
                last = newNode;
            }else {
                last.next = newNode;
                last = newNode;
            }
        }
    }
    public static void functionTwo(int[][] data, int m){
        GraphLink head[] = new GraphLink[m];
        for (int i = 1; i < m; i++) {
            head[i] = new GraphLink();
            System.out.print("顶点" + i + "=>");
            for (int j = 0; j < data.length; j++) {
                if (data[j][0] == i){
                    int dataNum = data[j][1];
                    head[i].insert(dataNum);
                }
            }
            head[i].print();
        }
    }


    public static void main(String[] args) {
        int[][] data = {{1,2},{2,1},{1,5},{5,1},{2,3},{3,2},{2,4},{4,2},{3,4},{4,3},{3,5},{5,3},{4,5},{5,4}};
        functionOne(data,6);
        System.out.println("**************************************");
        functionTwo(data, 6);
    }

}